<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { httpRequest } from "../../utils/http";
import {ref} from 'vue'
import drawQrcode from "../../utils/weapp.qrcode.esm.js"; //引入生成二维码插件


const item = ref('')
const url = ref('')
const src = ref('')
const width = ref('')
const height = ref('')
onLoad((e)=>{
	item.value = JSON.parse(e.item)
  console.log(item.value);
  getTaskList()
	publish(item.value.videoId)
  getCount()
  
})

 const publish = async(id) => {
      //loading
      uni.showLoading({
        title: "正在生成二维码",
        mask: true,
      });
      const res = await httpRequest("/api/uploadH5", "POST", { videoId: id });
      console.log(res);
      const video = res.data.video.videoUrl;
      const title = res.data.video.title;
      // const hashTags = res.data.video.label.split("#");
      const nonce_str = res.data.str;
      const timestamp = res.data.time;
      const signature = res.data.qian;
      // this.url = `snssdk1128://openplatform/share?client_key=awib1ol4e2732l27&nonce_str=${nonce_str}&timestamp=${timestamp}&signature=${signature}&share_type=h5&video_path=${video}&title=${title ? title : ""}`;
      url.value = `snssdk1128://openplatform/share?client_key=awib1ol4e2732l27&nonce_str=${nonce_str}&timestamp=${timestamp}&signature=${signature}&share_type=h5&video_path=${video}&share_to_publish=1&title=${
        title ? title : ""
      }`;

      //二维码
      // 提取查询参数部分
      const queryString = url.value.split("?")[1];
      // 分割查询参数字符串为键值对数组
      const paramsArray = queryString.split("&");
      // 对每个查询参数进行编码
      const encodedParamsArray = paramsArray.map((param) => {
        const [key, value] = param.split("=");
        const encodedValue = encodeURIComponent(value);
        return `${key}=${encodedValue}`;
      });

      // 构造编码后的查询参数字符串
      const encodedQueryString = encodedParamsArray.join("&");

      // 构造编码后的 URL
      const encodedUrl = url.value.split("?")[0] + "?" + encodedQueryString;
      console.log(encodedUrl);
      uni
        .createSelectorQuery()
        .select("#canvas")
        .boundingClientRect((data) => {
          console.log("获取到canvas元素的布局信息：", data);
          width.value = data.width;
          height.value = data.height;
          console.log('url',url.value);
          drawQrcode({
          width: width.value, // 必须，二维码宽度，与canvas的width保持一致
          height: height.value, // 必须，二维码高度，与canvas的height保持一致
          canvasId: "myQrcode",
          correctLevel:2,
          background: "#ffffff", //	非必须，二维码背景颜色，默认值白色
          foreground: "#000000", // 非必须，二维码前景色，默认值黑色 	'#000000'
          // ctx: wx.createCanvasContext('myQrcode'), // 非必须，绘图上下文，可通过 wx.createCanvasContext('canvasId') 获取，v1.0.0+版本支持
          text: encodedUrl, // 必须，二维码内容
        });
        console.log('画完了');
        setTimeout(() => {
        uni.canvasToTempFilePath({
          canvasId: "myQrcode",
          success: async(res) => {
            console.log(res.tempFilePath);
            codeSrc.value = res.tempFilePath
            const {data} =await uni.uploadFile({
				// url: 'https://www.diandianyouke.cn:8081/api/uploadErWeiMa',
				url: 'https://www.diandianyouke.cn:8081/api/uploadErWeiMa',
				filePath: res.tempFilePath,
				name: 'ewm',
				formData: {
					businessId:uni.getStorageSync('business').businessId
				},	
			})
			
			    console.log(JSON.parse(data).data);
					src.value = JSON.parse(data).data
          uni.hideLoading();
          },
        });
        
      }, 3000);
        })
        .exec();
    }

 //保存图片函数
 const saveImg = () => {
	uni.showLoading()
      //下载图片
      console.log(src.value);
      uni.downloadFile({
        url: src.value,
        success: (res) => {
          if (res.statusCode === 200) {
            //保存图片到系统相册
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                console.log(res);
				uni.hideLoading()
                uni.showToast({
                  title: "保存二维码成功",
                  icon: "none",
                });
              },
              fail: function (err) {
                console.log(err);
				uni.hideLoading()
                uni.showToast({
                  title: "保存二维码失败",
                  icon: "none",
                });
              },
            });
          } else {
            console.log(res);
			uni.hideLoading()
            uni.showToast({
              title: "下载失败",
              icon: "none",
            });
          }
        },
        fail: (fail) => {
          console.log(fail);
		  uni.hideLoading()
          uni.showToast({
            title: "下载失败",
            icon: "none",
          });
        },
      });
    }

	const change = async() => {
      const res = await httpRequest('/api/videoWhetherWhether','POST',{
        taskId:item.value.taskId,
        videoId:item.value.videoId
      })
      console.log(res);
      if(res.data==null){
        count.value = 0
        uni.showToast({title:'没有更多视频了',icon:'none'})
        return
      }
      item.value = res.data
      publish(item.value.videoId)
      getCount()
    }

    // const getVideoList = async() => {
    //   uni.showLoading({
    //     title: '加载中',
    //     mask: false
    //   })
    //   const res = await httpRequest("/api/videoListByTaskId", "POST", {
    //     taskId: item.value.taskId,
    //   });
    //   console.log(res);
    //   uni.hideLoading();
    // }

    const back = () => {
      uni.navigateBack({ delta: 1 })
    }

    const getNum = (e) => {
      if(e<10)return '0'+'0'+ e
      if(e>=10<100)return '0'+ e
      if(e>=100)return e
    }
    const name = ref('')
    const getTaskList = async() => {
      const res = await httpRequest("/api/taskListByShopId", "POST", {
        shopId: item.value.shopId,
      });
      console.log(res);
      name.value = res.data.filter(e=>e.id==item.value.taskId)[0].taskName
    }
    
    const count = ref(0)
    const getCount = async() => {
      count.value = 0
      const res = await httpRequest("/api/videoListByTaskId", "POST", {
        taskId: item.value.taskId,
      });
      res.data.videoList.forEach(e=>{
        if(e.whetherWhether=='2') count.value++
      })
    }
    
    const shareImg = ref('')
    const bgPath = ref('')
    const codeSrc = ref('')
    const share = () => {
      uni.showLoading()
      uni.getImageInfo({
        src: 'https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/ewma_img_logo_dddyk.png',
        success: ({ width, height, path, orientation, type }) => {
          console.log(width);
          console.log(height);
          bgPath.value = path
          console.log('下载成功');
          console.log(bgPath.value);
          const ctx = wx.createCanvasContext('shareCanvas');
    	//绘制背景色
        ctx.setFillStyle('#FAFAFA')
    	//背景图
        ctx.drawImage(bgPath.value, 0, 0, 315, 457)
        ctx.setFillStyle('#ffffff')
        ctx.fillRect(12, 59, 291, 317)
        ctx.drawImage(codeSrc.value, 20, 67, 275, 275)
        ctx.setFontSize(12)
        ctx.setFillStyle('#45464a')
        ctx.fillText("打开抖音，扫描二维码发布视频",65,360)
        ctx.setFillStyle('#fff')
        ctx.setFontSize(18)
        ctx.fillText(getNum(item.value.videoName),23,404)
        ctx.setFillStyle('#303133')
        ctx.setFontSize(14)
        ctx.fillText(name.value,145,404)
       ctx.draw();
       uni.hideLoading()
      uni.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'shareCanvas',
        success:(res)=>{
          console.log(res);
          shareImg.value = res.tempFilePath
          console.log('成功');
          wx.showShareImageMenu({
          	needShowEntrance:true,
          	path: res.tempFilePath,
          	success: function (res) {
              
          		console.log("success:" + JSON.stringify(res));
          	},
          	fail: function (err) {
              uni.hideLoading()
          		console.log("fail:" + JSON.stringify(err));
          	}
          });
        },
        error:(err)=>{
          console.log(err);
        }
      })
        },
        fail: (error) => {
          console.log('下载失败'+error);
        }
      })
      
    }
</script>

<template>
  <scroll-view scroll-y class="page">
	<view class="center">
		<view class="code">
			<image style="width: 550rpx;height: 550rpx;" :src="src"/>
			<text>打开抖音,扫描二维码发布视频</text>
		</view>
		<view class="num">
			<text>{{ getNum(item.videoName) }}</text>
			<text class="name">{{name}}</text>
		</view>
	</view>
	<view class="bottom">
		<view class="share" @click="share">
			<image style="width: 96rpx;height: 96rpx;margin-bottom: 18rpx;" src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/ewma_icon_fxiang.png"/>
			<text>分享</text>
		</view>
		<view class="share" @click="change">
			<image style="width: 96rpx;height: 96rpx;margin-bottom: 18rpx;" src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/ewma_icon_hyge.png"/>
			<text>换一个</text>
			<text>剩余{{ count }}条</text>
		</view>
		<view class="share" @click="saveImg">
			<image style="width: 96rpx;height: 96rpx;margin-bottom: 18rpx;" src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/ewma_icon_xzai.png"/>
			<text>保存</text>
		</view>
	</view>
	<view class="x">
		<image @click="back" style="width: 64rpx;height: 64rpx;" src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/tuomingcha.png"/>
	</view>
  </scroll-view>
  <canvas
    style="width: 550rpx; height: 550rpx; margin: 0 auto; top: -99999px"
    id="canvas"
    canvas-id="myQrcode"
  ></canvas>
  <canvas
    style="width: 315px;height: 457px;top: -99999px"
    id="share"
    canvas-id="shareCanvas"
  ></canvas>
</template>

<style lang="scss">
	.page{
		position: fixed;
		width: 100%;
		height: 100%;
		background-image: url(https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/erweima_img_bg5.jpg);
		background-size: 100% 100%;
		.center{
			width: 630rpx;
			height: 914rpx;
			background-image: url(https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/ewma_img_logo_dddyk.png);
			background-size: 100% 100%;
			margin: 140rpx 58rpx 0;
			padding-top: 118rpx;
			box-sizing: border-box;
			
			.code{
				margin: 0 24rpx 0;
				width: 582rpx;
				height: 634rpx;
				padding: 16rpx;
				font-size: 24rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				color: rgb(69,70,74);
				background-color: #fff;
				box-sizing: border-box;
			}
			.num{
				width: 582rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 30rpx;
				font-size: 36rpx;
				font-weight: 700;
				color: #fff;
				margin: 30rpx 24rpx 0;
				.name{
					font-size: 28rpx;
					color: rgb(48,49,51);
					font-weight: normal;
				}
			}
		}
		.bottom{
			width: 592rpx;
			height: 200rpx;
			display: flex;
			justify-content: space-between;
			margin-top: 60rpx;
			margin-left: 80rpx;
			font-size: 30rpx;
			color: #fff;
			.share{
				display: flex;
				flex-direction: column;
				align-items: center;
			}
		}
		.x{
			margin-top: 76rpx;
			text-align: center;
		}
	}
</style>


